package com.weiyuwqj.web;

import com.weiyuwqj.utils.CreateImageCode;
import com.weiyuwqj.utils.VerifyCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by yandq on 15/12/6.
 */

public class ImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /* 创建二进制的输出流 */
        ServletOutputStream sos = response.getOutputStream();
        HashMap<String, Object> map = VerifyCodeUtil.getInstance().getVerifyCode();
        String sRand = (String) map.get("sRand");
        CreateImageCode c=new CreateImageCode(150,40,4,5);
        request.getSession().setAttribute("verifyCode", c.getCode());
        request.getSession().setAttribute("verifyCodeTime",new Date());

        byte[] b = (byte[]) map.get("bImage");

        /* 将生成的字符串存储在cookie中 */
        // CookieUtils.fillRandomCode(request,response, sRand,
        // getCookiePath(request),CookieUtils.COOKIE_MAX_AGE_CURRENTSESSION);
        /* 禁止图像缓存 */

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //sos.write(b);

        c.write(sos);

        sos.flush();
        sos.close();
        return;
    }

    public String getCookiePath(HttpServletRequest request) {
        String path = request.getContextPath();
        // System.out.println("path="+path);
        if ("".equals(path)) {
            path = "/";
        }
        return path;
    }
}
